<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form ref="queryForm" :model="queryParams" size="small" :inline="true" label-width="68px">
      <el-form-item>
        <el-select v-model="queryParams.term" placeholder="请选择学期">
          <el-option
            v-for="item in term"
            :key="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input v-model="queryParams.courseName" placeholder="请输入课程名称" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="onSubmit">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="clear">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="dialogVisible = true">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini">批量删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-upload2" size="mini" @click="handleImport">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-col>
    </el-row>

    <!--添加数据对话框表单-->
    <el-dialog title="编辑专业" :visible.sync="dialogVisible" width="30%">
      <el-form ref="form" :model="course" :rules="rules" label-width="80px" size="mini">
        <el-form-item label="课程名称" prop="courseName">
          <el-input v-model="course.courseName" />
        </el-form-item>

        <el-form-item label="所属学期" prop="term">
          <el-select v-model="course.term" placeholder="请选择">
            <el-option
              v-for="item in term"
              :key="item"
              :value="item"
            />
          </el-select>
        </el-form-item>

        <el-form-item style="margin-left: 50px">
          <el-button type="primary" @click="add()">提交</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip text-center">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size:12px;vertical-align: baseline;"
            @click="importTemplate"
          >下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 表格 -->
    <el-table
      ref="multipleTable"
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" style="width: 50px" />
      <el-table-column prop="courseName" label="课程名称" align="center" />
      <el-table-column prop="term" label="学期" align="center" />
      <el-table-column prop="createUserName" label="创建人" align="center" />
      <el-table-column prop="createTime" label="创建时间" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime ? parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}") : '' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="更新时间" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.updateTime ? parseTime(scope.row.updateTime, "{y}-{m}-{d} {h}:{i}") : '' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="300px">
        <template slot-scope="scope">
          <el-button size="small" type="text" icon="el-icon-edit" @click="update(scope.row.id)">修改</el-button>
          <el-button size="small" type="text" icon="el-icon-delete" @click="deleteById(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页工具条-->
    <el-pagination
      :background="background"
      :current-page="current"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="5"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalCount"
      style="margin-top: 8px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { parseTime } from '@/utils'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import {
  deleteUserCourseUsingPost,
  getByIdUsingGet7,
  pageUsingPost5,
  saveUsingPost7,
  updateUsingPut6
} from '@/api/user_course'
import { list } from '@/api/schoolyear'

export default {
  data() {
    return {
      deptOptions: undefined,
      options: [{
        value: '1',
        label: '学院'
      }, {
        value: '2',
        label: '系部'
      }, {
        value: '3',
        label: '专业'
      }
      ],
      value: '',
      background: true,
      // 每页显示的条数
      pageSize: 5,
      // 总记录数
      totalCount: 100,
      // 当前页码
      current: 1,
      // 添加数据对话框是否展示的标记
      dialogVisible: false,
      avatar:
        'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
      queryParams: {
        courseName: ''
      },
      course: {
        courseName: '',
        term: ''
      },
      term: [],
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { token: getToken() },
        // 上传的地址B
        url: process.env.VUE_APP_BASE_API + 'user/excel-input'

      },
      rules: {
        courseName: [
          { required: true, message: '请输入课程名称', trigger: 'blur' }
        ],
        term: [
          { required: true, message: '请选择学期', trigger: 'blur' }
        ]
      },
      multipleSelection: [],
      filename: '',
      tableData: [],
      list: null,
      total: 0,
      listQuery: {
        page: 1,
        limit: 20,
        importance: undefined,
        title: undefined,
        type: undefined,
        sort: '+id'
      }
    }
  },
  created() {
  },
  mounted() {
    this.page() // 当页面加载完成后，发送异步请求，获取数据
  },
  methods: {
    handleClose() {
      this.dialogVisible = false
      this.major = { name: '', type: '', parentId: '' }
    },
    // 查询分页数据
    page() {
      const requestData = {
        courseName: this.queryParams.courseName,
        term: this.queryParams.term,
        createUserId: this.queryParams.createUserId,
        current: this.current,
        pageSize: this.pageSize
      }

      // test
      // query(1849111290593714178).then(res =>  {
      //   console.log("res", res
      //   )
      // })

      pageUsingPost5(requestData)
        .then((res) => {
          console.log('requestData', requestData)

          this.totalCount = res.data.total
          console.log('res', res)

          this.tableData = res.data.records
        })
        .catch((error) => {
          // 处理错误情况
          console.error('Error fetching data:', error)
        })

      list().then(res => {
        this.term = res.data.map(item => item.term)
        console.log('=======term', this.term)
      })
    },

    // 复选框选中后执行的方法
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    /** 导出按钮操作 */
    handleExport() {
      // 选中数据时下载选择数据
      if (this.multipleSelection.length > 0) {
        this.queryParams.ids = this.multipleSelection.map((item) => item.id) // 传递筛选后的id数组
        this.filename = '选中教师-' + new Date().getTime() + '.xlsx'
        // eslint-disable-next-line no-empty
      } else {
        this.queryParams.ids = [] // 传递空数组
        if (this.queryParams.name === '' && this.queryParams.number === '' && this.queryParams.phoneNumber === '' && this.queryParams.email === '') {
          this.filename = '全部教师-' + new Date().getTime() + '.xlsx'
          // eslint-disable-next-line no-empty
        } else {
          this.filename = '筛选教师-' + new Date().getTime() + '.xlsx'
        }
      }
      this.download(process.env.VUE_APP_BASE_API + '/user/excel-output', this.queryParams, this.filename)
      // this.download(process.env.VUE_APP_BASE_API + '/user/excel-output', this.queryParams, `user_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = '用户导入'
      this.upload.open = true
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(process.env.VUE_APP_BASE_API + '/user/template', {
      }, `教师信息模板.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg ? response.msg : response.data + '</div>', '导入结果', { dangerouslyUseHTMLString: true })
      this.getList()
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    },
    // 查询方法
    onSubmit() {
      this.current = 1
      this.page()
    },

    clear() {
      this.queryParams = { number: '', name: '', phoneNumber: '' }
      this.page()
    },

    // 添加数据
    add() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          let operator

          if (this.course.id) {
            // 修改
            operator = updateUsingPut6(this.course)
          } else {
            operator = saveUsingPost7(this.course)
          }

          operator.then((resp) => {
            if (resp.code == '1') {
              this.dialogVisible = false
              this.page()
              this.$message({ message: '恭喜你，保存成功', type: 'success' })
              this.course = {}
            } else {
              this.$message.error(resp.msg)
            }
          })
        }
      })
    },
    update(id) {
      // 1. 打开窗口
      this.dialogVisible = true
      // 2. 发送请求
      getByIdUsingGet7(id).then((result) => {
        if (result.code == 1) {
          this.course = result.data
        } else {
          this.$message.error('获取用户信息失败')
        }
      })
    },
    // 分页
    handleSizeChange(val) {
      // 重新设置每页显示的条数
      this.pageSize = val
      this.page()
    },

    handleCurrentChange(val) {
      // 重新设置当前页码
      this.current = val
      this.page()
    },

    // 删除员工信息
    deleteById(id) {
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 2. 发送AJAX请求
          deleteUserCourseUsingPost({ id }).then((resp) => {
            if (resp.code == 1) {
              // 删除成功
              this.$message.success('恭喜你，删除成功')
              this.page()
            } else {
              this.$message.error(resp.msg)
            }
          })
        })
        .catch(() => {
          // 用户点击取消按钮
          this.$message.info('已取消删除')
        })
    },

    formatJson(filterVal) {
      return this.list.map((v) =>
        filterVal.map((j) => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
